package hk.com.fgoproduction.getdroplets.Lib.FileMan

import android.os.Bundle
import java.io.File
import java.util.*

/***
 * File Manager class
 */
class FileMan {

    /***
     * List matching policy:
     * ArrayList item sorting in ascending order
     * Value of ArrayList item is the key of HashMap path
     * Finally the absolute path could be obtained
     *
     * For root(/) and parent path (../), spacial handling will be carried out by corresponding class
     */

    private val item = ArrayList<String>() //The name of path
    private val folderList = ArrayList<String>() //Store folder item only
    private val fileList = ArrayList<String>() //Store file item only
    private val path = HashMap<String, String>() //The path

    companion object {
        val ROOT = "/mnt/sdcard" //Common ROOT for file manager
    }

    /***
     * Used to generate directory list on specific path
     *
     * @param dir Destination path
     * @return bundle that contain @param item and @param path
     * @see clearAllList
     */
    fun getDirMap(dir: String, root: String = ROOT): Bundle {
        clearAllList()

        val f = File(dir)
        val files: Array<File> = f.listFiles()

        if (!dir.equals(root)) {
            folderList.add("/")
            path.put("/", root)

            folderList.add("../")
            path.put("../", f.parent)
        }


        path.putAll(files.associateBy({it.name}, {it.absolutePath}))
        //path.putAll(files.map { it.name to it.absolutePath }) /*This is slower*/
        folderList.addAll(files.filter { it.isDirectory }.map { it.name + "/" })
        fileList.addAll(files.filter { !it.isDirectory }.map { it.name })

        /*
        for (i in files.indices) {
            val file = files[i]
            path.put(file.name, file.absolutePath)

            if (file.isDirectory) {
                folderList.add(file.name + "/")
            } else {
                fileList.add(file.name)
            }
        }
        */

        Collections.sort(folderList)
        Collections.swap(folderList, 0, 1) //0->"/", 1->"../"
        Collections.sort(fileList)
        item.addAll(folderList)
        item.addAll(fileList)

        val bundle = Bundle()
        bundle.putSerializable("item", item)
        bundle.putSerializable("path", path)

        return bundle
    }

    /**
     * Empty four list for reusing
     * @see getDirMap
     */
    private fun clearAllList() {
        if (!item.isEmpty()) item.clear()
        if (!path.isEmpty()) path.clear()
        if (!folderList.isEmpty()) folderList.clear()
        if (!fileList.isEmpty()) fileList.clear()
    }

}